﻿using GC_RF.DataAccess.Abstractions.Interfaces.Factories;
using GC_RF.DataAccess.Abstractions.Interfaces.Helpers;
using System;
using System.Data.Entity.Core.Objects;

namespace GC_RF.DataAccess.Helpers
{
	public class UnitOfWork : IUnitOfWork, IDisposable
	{
		#region Variables

		private bool _isDisposed;

		#endregion

		#region Constructors

		public UnitOfWork(IDbContextFactory contextFactory)
		{
			if (contextFactory == null)
				throw new ArgumentNullException(string.Format("contextFactory"));

			Context = contextFactory.GetContext();
			if (Context == null)
				throw new ArgumentNullException(string.Format("context"));
		}

		#endregion

		#region IUnitOfWork Members

		public ObjectContext Context { get; private set; }

		public void SaveChanges()
		{
			if (Context != null)
			{
				Context.SaveChanges();
			}
		}

		#endregion

		#region IDisposable Members

		protected virtual void Dispose(bool disposing)
		{
			if (!_isDisposed)
			{
				if (disposing)
				{
					Context.Dispose();
				}
			}
			_isDisposed = true;
		}

		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		#endregion
	}
}
